define(function (require) {
    require('bootstrapValidator');
    require('messager');
    require('table');
    require('typeahead');
    require('doctor-data');
    require('fileinput');
    require('daterangepicker');
    require('doctor-select');
    require('moment');
    require('clockpicker');
    require('datetimepicker');
    require('iCheck');

    $.module("BASE.BDMVoucher", function () {

        return {
            init: function () {
                this.loadData();
                this.loadEvent();
            },
            clearDatas:function () {
                var that = this;

                $("#_id").val(0);
                $('#CompanyId').val('');
                $('#PeriodId').val('');
                $('#PeriodCode').val('');
                $('#PeriodYear').val('');
                $('#PeriodMonth').val('');
                $('#VoucherTypeId').val('');
                $('#VoucherTypeName').val('');
                $('#SourceSys').val('');
                $('#SourceType').val('');
                $("input[name='AROtherBillType'][value='1']").iCheck('check');
                $('#BookedDate').val('');

                $("input[name='BizStatus'][value='0']").iCheck('check');
                $('#JournalEntryId').val('');
                $('#JournalEntryAuxiliaryAcc_id').val('');
                $('#CustomerId').val('');
                $('#CustomerInternalCompanyId').val('');
                $('#SupplierId').val('');
                $('#SupplierInternalCompanyId').val('');
                $('#CostCenterId').val('');
                $('#CostCenterName').val('');
                $('#AccountViewCode').val('');
                $('#AccountViewName').val('');
                $('#GroupAccountViewCode').val('');
                $('#Debit').val(0);
                $('#Credit').val(0);
                $('#Remark').val('');
                $('#VoucherId').val('');
                $('#VoucherCode').val('');
                $('#SourceOperation').val('');

                $("input[name='SourceOperation'][value='1']").iCheck('check');
                $("input[name='GroupAccountViewCodeBelong'][value='0']").iCheck('check');

                $('#fm').bootstrapValidator('resetForm', true);
                that.showDiv('main_div');
            },
            loadData: function (pageNumber, pageSize) {
                var that = this;

                let s_id = $("#s_id").val();
                let s_VoucherCode = $("#s_VoucherCode").val();
                let s_VoucherTypeName = $("#s_VoucherTypeName").val();
                let s_CostCenterName = $("#s_CostCenterName").val();
                let s_AccountViewCode = $("#s_AccountViewCode").val();
                let s_AccountViewName = $("#s_AccountViewName").val();

                SYS.Core.ajax({
                    url: "base/voucher/list",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        VoucherCode: s_VoucherCode,
                        VoucherTypeName: s_VoucherTypeName,
                        CostCenterName: s_CostCenterName,
                        AccountViewCode: s_AccountViewCode,
                        AccountViewName: s_AccountViewName,
                    },
                    success: function (data) {
                        var obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };

                        $("#myTable").bootstrapTable('destroy');
                        $('#myTable').bootstrapTable({
                            striped: true,
                            singleSelect: false,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination: 'server',
                            clickToSelect: true,
                            idField: 'id',
                            data: obj.data,
                            columns: [
                                // {field: 'checked', checkbox: true} ,
                                {field: 'Id', title: '编号', align: 'center'},
                                {field: 'CompanyId', title: '法人公司', align: 'center'},
                                {field: 'CostCenterId', title: '成本中心（部门）', align: 'center'},
                                {field: 'CostCenterName', title: '成本中心名称', align: 'center'},
                                {field: 'AccountViewCode', title: '科目代码（法人公司）', align: 'center'},
                                {field: 'AccountViewName', title: '科目名称（法人公司）', align: 'center'},
                                {field: 'PeriodId', title: '会计期间', align: 'center'},
                                {field: 'PeriodCode', title: '会计期间编号', align: 'center'},
                                {field: 'PeriodYear', title: '会计期间年', align: 'center'},
                                {field: 'PeriodMonth', title: '会计期间月', align: 'center'},
                                {field: 'VoucherTypeId', title: '凭证类型Id', align: 'center'},
                                {field: 'VoucherTypeName', title: '凭证类型Name', align: 'center'},
                                // {field: 'SourceSys', title: '来源系统', align: 'center'},
                                // {field: 'SourceType', title: '来源类型', align: 'center'},
                                {field: 'AROtherBillType', title: '应收单类型', align: 'center',
                                    formatter:function (val,row) {
                                        let html = '';
                                        if (val == 1){
                                            html = '应收发票'
                                        } else if (val == 2){
                                            html = '销售出库'
                                        } else if (val == 3){
                                            html = '成本调整单'
                                        } else if (val == 99) {
                                            html = '其它'
                                        }
                                        return html;
                                    }
                                },

                                {field: 'BookedDate', title: '记账日期', align: 'center'},
                                {field: 'BizStatus', title: '状态', align: 'center',
                                    formatter:function (val,row) {
                                        let html = '';
                                        if (val == 0){
                                            html = '暂存'
                                        } else if (val == 1){
                                            html = '已提交'
                                        } else if (val == 2){
                                            html = '已作废'
                                        } else if (val == 3){
                                            html = '已审核'
                                        } else if (val == 5){
                                            html = '已过账'
                                        }
                                        return html;
                                    }
                                },
                                {field: 'JournalEntryId', title: '凭证分录Id', align: 'center'},
                                {field: 'JournalEntryAuxiliaryAcc_id', title: '辅助核算行Id', align: 'center'},
                                {field: 'CustomerId', title: '客户Id', align: 'center'},
                                {field: 'CustomerInternalCompanyId', title: '客户', align: 'center'},
                                {field: 'SupplierId', title: '供应商Id', align: 'center'},
                                {field: 'SupplierInternalCompanyId', title: '供应商', align: 'center'},

                                {field: 'Debit', title: '借方', align: 'center'},
                                {field: 'Credit', title: '贷方', align: 'center'},
                                {field: 'Remark', title: '行摘要', align: 'center'},
                                {field: 'VoucherId', title: '凭证ID', align: 'center'},
                                {field: 'VoucherCode', title: '凭证号', align: 'center'},
                                {field: 'SourceOperation', title: '状态', align: 'center',
                                    formatter:function (val,row) {
                                        let html = '';
                                        if (val == 1){
                                            html = '系统'
                                        } else if (val == 2){
                                            html = '人工'
                                        }
                                        return html;
                                    }
                                },

                                // {
                                //     field: 'do', title: '操作', align: 'center',
                                //     formatter: function (value, row, index) {
                                //         var html = '';
                                //         html += '<a href="javascript:void(0)" onclick="BASE.BDMVoucher.toEdit(' + row.Id + ')" class="btn btn-edit">编辑</a> | ';
                                //         html += '<a href="javascript:void(0)" onclick="BASE.BDMVoucher.toRemove(' + row.Id + ')" class="btn btn-remove  ">删除</a>';
                                //         return html;
                                //     }
                                // }
                            ],
                            onPageChange: function(number, size){
                                that.loadData(number, size);
                            },
                            onRefreshTable: function () {
                                that.loadData();
                            },
                            onClickCell: function (field, value, row, $element) {
                            }
                        });
                    }
                });
            },
            loadEvent: function () {
                var that = this;

                // 定义编辑框form
                var $form = $("#fm");

                $(".i-checks").iCheck({checkboxClass:"icheckbox_square-orange", radioClass:"iradio_square-orange"});

                // 查询
                $("#search-toolbar").on('click', "#btn_search", function () {
                    that.loadData();
                }).on("keydown ", "input", function (e) {
                    if (e.keyCode == 13) {
                        that.loadData();
                    }
                });

                //批量删除
                $("#btn_deletes").on('click',function(){
                    that.toRemoves();
                });

                // 保存新增
                $("#btn_contiune_add").on('click', function () {
                    // 不用关闭当前编辑框
                    that.save();
                });

                // 新增
                $("#btn_add").on('click', function () {
                    that.clearDatas();

                    $("#btn-add-div").show();
                    $("#btn-edit-div").hide();
                    that.showDiv('edit_div');
                });

                // 绑定日期控件
                $("#BookedDate").datetimepicker({
                    minView: "hour",
                    format: 'yyyy-mm-dd',
                    todayBtn: true,
                    language: 'zh-CN', // 汉化
                    autoclose: true    // 选择日期后自动关闭
                }).on('changeDate', function (ev) {
                    var field = $(this).attr("id");
                    $form.find("input[data-field='" + field + "']").val(ev.date.getTime());
                });

                // 关联公司
                $("#CompanyId").on('click', function () {
                    DOCTOR.Select.showCompany(this);
                });
                // 成本中心
                $("#CostCenterId").on('click', function () {
                    DOCTOR.Select.showCostCenter(this);
                });
                // 科目
                $("#AccountViewCode").on('click', function () {
                    DOCTOR.Select.showAccountView(this);
                });
                // 会计期间
                $("#PeriodId").on('click', function () {
                    DOCTOR.Select.showPeriod(this);
                });

                // 返回
                $(".back_list").on('click', function () {
                    that.clearDatas();

                    that.showDiv('main_div');
                });

                //
                $('#fm').bootstrapValidator({
                    excluded: ':disabled',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        // title: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         }
                        //     }
                        // },
                        // order: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         },
                        //         regexp: {
                        //             regexp: /^[1-9]\d*$/i,
                        //             message: '格式不正确，必须大于0'
                        //         }
                        //     }
                        // }
                    }
                }).on('success.form.bv', function (e) {
                    e.preventDefault();

                    let CompanyId = $("#CompanyId").attr('data-id') || "";
                    let CostCenterId = $("#CostCenterId").attr('data-id') || "";
                    let AccountViewCode = $("#AccountViewCode").attr('data-id') || "";
                    let PeriodId = $("#PeriodId").attr('data-id') || "";
                    let BookedDate = $("#BookedDate").val() || "";

                    if(CompanyId === "") {
                        $.messager.popup("请选择一个公司，在提交", 'error');
                        $('#fm').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }
                    if(CostCenterId === "") {
                        $.messager.popup("请选择一个成本中心（部门），在提交", 'error');
                        $('#fm').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }
                    if(AccountViewCode === "") {
                        $.messager.popup("请选择一个科目代码(法人公司)，在提交", 'error');
                        $('#fm').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }
                    if(PeriodId === "") {
                        $.messager.popup("请选择一个会计期间，在提交", 'error');
                        $('#fm').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }
                    if(BookedDate === "") {
                        $.messager.popup("请选择一个记账日期，在提交", 'error');
                        $('#fm').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }

                    that.save();
                });

            },
            save: function () {
                var that = this;

                let id = $("#_id").val();
                let companyId = $("#CompanyId").attr('data-id') || 0;
                let costCenterId = $("#CostCenterId").attr('data-id') || 0;
                let costCenterName = $("#CostCenterId").val();
                let accountViewCode = $("#AccountViewCode").attr('data-id');
                let accountViewName = $("#AccountViewCode").val();
                let groupAccountViewCode = $("#AccountViewCode").val();
                let periodId = $("#PeriodId").attr('data-id') || 0;
                let periodCode = $("#PeriodCode").val();
                let periodYear = $("#PeriodYear").val();
                let periodMonth = $("#PeriodMonth").val();
                let voucherTypeId = $("#VoucherTypeId").val();
                let voucherTypeName = $("#VoucherTypeName").val();
                // let sourceSys = $("#SourceSys").val();
                // let sourceType = $("#SourceType").val();
                let aROtherBillType = $("input[name='AROtherBillType']:checked").val();
                let bookedDate = $("#BookedDate").val();
                let bizStatus = $("input[name='BizStatus']:checked").val();
                let journalEntryId = $("#JournalEntryId").val();
                let journalEntryAuxiliaryAcc_id = $("#JournalEntryAuxiliaryAcc_id").val();
                let customerId = $("#CustomerId").val();
                let customerInternalCompanyId = $("#CustomerInternalCompanyId").val();
                let supplierId = $("#SupplierId").val();
                let supplierInternalCompanyId = $("#SupplierInternalCompanyId").val();
                let debit = $("#Debit").val();
                let credit = $("#Credit").val();
                let remark = $("#Remark").val();
                let voucherId = $("#VoucherId").val();
                let voucherCode = $("#VoucherCode").val();
                let sourceOperation = $("input[name='SourceOperation']:checked").val();
                let groupAccountViewCodeBelong = $("input[name='GroupAccountViewCodeBelong']:checked").val();

                SYS.Core.ajax({
                    url: 'base/voucher/save',
                    common: {},
                    data:{
                        Id: id || 0,
                        CompanyId: companyId,
                        CostCenterId: costCenterId,
                        CostCenterName: costCenterName,
                        AccountViewCode: accountViewCode,
                        AccountViewName: accountViewName,
                        GroupAccountViewCode: groupAccountViewCode,
                        PeriodId: periodId,
                        PeriodCode: periodCode,
                        PeriodYear: periodYear,
                        PeriodMonth: periodMonth,
                        VoucherTypeId: voucherTypeId,
                        VoucherTypeName: voucherTypeName,
                        SourceSys: -1,
                        SourceType: -1,
                        AROtherBillType: aROtherBillType,
                        BookedDate: bookedDate,
                        BizStatus: bizStatus,
                        JournalEntryId: journalEntryId,
                        JournalEntryAuxiliaryAcc_id: journalEntryAuxiliaryAcc_id,
                        CustomerId: customerId,
                        CustomerInternalCompanyId: customerInternalCompanyId,
                        SupplierId: supplierId,
                        SupplierInternalCompanyId: supplierInternalCompanyId,
                        Debit: debit,
                        Credit: credit,
                        Remark: remark,
                        VoucherId: voucherId,
                        VoucherCode: voucherCode,
                        SourceOperation: sourceOperation,
                        GroupAccountViewCodeBelong: groupAccountViewCodeBelong,
                    },
                    success: function (data) {
                        if(data.code == 1) {
                            $.messager.popup(data.msg, 'success');

                            that.loadData();
                            that.showDiv('main_div');
                        } else {
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg, 'error');
                        }
                    }
                })
            },
            toEdit: function (id) {
                var that = this;
                that.clearDatas();
                $("#btn-add-div").hide();
                $("#btn-edit-div").show();

                SYS.Core.ajax({
                    url: 'base/voucher/detail',
                    common: {},
                    data: {
                        Id: id ? id : 0
                    },
                    success: function (data) {
                        if (data.code == 1) {
                            var obj = data.data;
                            let id = obj.Id;

                            let companyId = obj.CompanyId;
                            let costCenterId = obj.CostCenterId;
                            let companyName = obj.CompanyName;
                            let costCenterName = obj.CostCenterName;
                            let accountViewCode = obj.AccountViewCode;
                            let accountViewName = obj.AccountViewName;
                            let groupAccountViewCode = obj.GroupAccountViewCode;

                            let periodId = obj.PeriodId;
                            let periodCode = obj.PeriodCode;
                            let periodYear = obj.PeriodYear;
                            let periodMonth = obj.PeriodMonth;
                            let voucherTypeId = obj.VoucherTypeId;
                            let voucherTypeName = obj.VoucherTypeName;
                            let sourceSys = obj.SourceSys;
                            let sourceType = obj.SourceType;
                            let aROtherBillType = obj.AROtherBillType;
                            let bookedDate = obj.BookedDate;
                            let bizStatus = obj.BizStatus;
                            let journalEntryId = obj.JournalEntryId;
                            let journalEntryAuxiliaryAcc_id = obj.JournalEntryAuxiliaryAcc_id;
                            let customerId = obj.CustomerId;
                            let customerInternalCompanyId = obj.CustomerInternalCompanyId;
                            let supplierId = obj.SupplierId;
                            let supplierInternalCompanyId = obj.SupplierInternalCompanyId;

                            let debit = obj.Debit;
                            let credit = obj.Credit;
                            let remark = obj.Remark;
                            let voucherId = obj.VoucherId;
                            let voucherCode = obj.VoucherCode;
                            let sourceOperation = obj.SourceOperation;
                            let groupAccountViewCodeBelong = obj.GroupAccountViewCodeBelong;

                            $("#_id").val(id);
                            $("#CompanyId").val(companyName).attr('data-id', companyId);
                            $("#CostCenterId").val(costCenterName).attr('data-id', costCenterId);
                            $("#AccountViewCode").val(accountViewName).attr('data-id', accountViewCode);
                            $("#PeriodId").attr('data-id', periodId).val(periodCode);
                            $("#PeriodCode").val(periodCode);
                            $("#PeriodYear").val(periodYear);
                            $("#PeriodMonth").val(periodMonth);
                            $("#VoucherTypeId").val(voucherTypeId);
                            $("#VoucherTypeName").val(voucherTypeName);
                            // $("#SourceSys").val(sourceSys);
                            // $("#SourceType").val(sourceType);
                            $("input[name='AROtherBillType'][value='" + (aROtherBillType != null ? aROtherBillType : 1) + "']").iCheck('check');
                            $("#BookedDate").val(bookedDate);
                            $("input[name='BizStatus'][value='" + (bizStatus != null ? bizStatus : 0) + "']").iCheck('check');
                            $("#JournalEntryId").val(journalEntryId);
                            $("#JournalEntryAuxiliaryAcc_id").val(journalEntryAuxiliaryAcc_id);
                            $("#CustomerId").val(customerId);
                            $("#CustomerInternalCompanyId").val(customerInternalCompanyId);
                            $("#SupplierId").val(supplierId);
                            $("#SupplierInternalCompanyId").val(supplierInternalCompanyId);

                            $("#Debit").val(debit);
                            $("#Credit").val(credit);
                            $("#Remark").val(remark);
                            $("#VoucherId").val(voucherId);
                            $("#VoucherCode").val(voucherCode);
                            $("#SourceOperation").val(sourceOperation);
                            $("#GroupAccountViewCodeBelong").val(groupAccountViewCodeBelong);
                            $("input[name='SourceOperation'][value='" + (sourceOperation != null ? sourceOperation : 1) + "']").iCheck('check');
                            $("input[name='GroupAccountViewCodeBelong'][value='" + (groupAccountViewCodeBelong != null ? groupAccountViewCodeBelong : 0) + "']").iCheck('check');

                            that.showDiv('edit_div');
                        }
                    }
                });
            },
            showDiv: function (div) {
                var divs = ['main_div','edit_div','import_div'];
                for(var i=0; i<divs.length; i++){
                    $("#" + divs[i]).hide();
                }
                $("#" + div).show();
            }
        }
    });
    BASE.BDMVoucher.init();
});